<template>
  <div class="paper__update__container">
    <div class="header">
      <div class="el-icon-back" @click="close"></div>
      <div class="tabs_box">{{ title }}</div>
      <div class="btns">
        <!-- <el-button round @click="savePrepareClass" :disabled="prepareLesson === '' && prepareLesson.id === null " v-if="!prepareLesson.checkStatus || prepareLesson.checkStatus === 0">提交备课</el-button> -->
        <!-- <el-button round @click="savePrepareClass" v-if="prepareLesson.checkStatus === 1"  >已提交</el-button> -->
        <!-- <el-button round v-if="prepareLesson.checkStatus === 2" disabled>已备课</el-button> -->

        <!-- *******************已通过******************* -->

        <el-button class="keep_btns" v-show="isKeep" type="text"
          >自动保存...</el-button
        >
        <el-button
          round
          v-if="
            [0, 5].includes(prepareLesson.checkStatus) ||
            !prepareLesson.checkStatus
          "
          @click="savePrepareClass"
          >提交备课</el-button
        >

        <el-button
          round
          v-if="[2, 4].includes(prepareLesson.checkStatus)"
          @click="toteach"
          >去上课</el-button
        >
        <!-- 审核中 -->
        <el-button
          round
          v-if="[1, 3, 2, 4].includes(prepareLesson.checkStatus)"
          @click="resentPrepareHandler"
          >重新备课</el-button
        >
      </div>
    </div>

    <div class="papers-content">
      <div>
        <div class="menu-list">
          <ul>
            <li
              v-for="(item, index) in tabCountList"
              :key="index"
              :class="[
                isbg === item.type ? 'menu-bg' : 'normal-menu-bg',
                item.type === 0 || item.type === 6 ? 'light-menu-bg' : '',
                (item.type === 0 && isbg !== 6) ||
                (item.type === 6 && isbg === item.type)
                  ? 'first-menu-bg'
                  : '',
              ]"
              @click="onMenuHandle(item, index)"
              v-show="item.num"
            >
              <div
                class="choose-tag"
                v-if="item.type !== 0 && item.type !== 6"
              ></div>
              <div>{{ item.name }}</div>
              ({{ item.num }})
            </li>
          </ul>
        </div>
        <div class="menu-card">
          <div
            :class="{ 'menu-card-bg': isCardbg == index }"
            @click="onCardHandle(item, index)"
            v-for="(item, index) in allFileList"
            :key="index"
          >
            <!-- <img src="/src/assets/course.png" alt=""> -->
            <!-- <img
              v-if="
                item.ext !== 'mp3' &&
                item.ext !== 'zip' &&
                item.ext !== 'rar' &&
                item.mediaType == null
              "
              :src="`${domain}${item.imgPath}`"
              alt="点津问道标品"
            /> -->
            <img
              v-if="item.imgPath"
              :src="`${domain}${item.imgPath}`"
              alt="点津问道标品"
            />
            <img
              v-else
              src="/src/assets/prepare-teach/weizhiwenjian.png"
              alt="点津问道标品"
            />
            <el-tooltip
              class="item"
              effect="dark"
              :content="item.fileName || item.title"
              placement="right"
              ><p>{{ item.fileName || item.title }}</p></el-tooltip
            >
          </div>
        </div>
      </div>
      <div>
        <div class="page-content">
          <div class="page-html-video">
            <el-empty v-if="tabCountList && tabCountList[0] && tabCountList[0].num === 0 " description="无资料" />
            <div class="a-edit-content" v-if="currentFile && currentFile.ext === 'html'">
              <AEditContent :handout="currentFile && currentFile.id" :classPreview="true"/>
            </div>
            <iframe allowfullscreen="true" :src="iframePath" frameborder="0" id="course-iframe" style="width: 100%; height: calc(100vh - 60px)" ref="paperDom" v-else-if="currentFile && currentFile.sourceFrom"/>
            <!-- <el-empty
              description="无资料"
            ></el-empty> -->
            <PageView v-else :currentFile="currentFile" />
          </div>
          <!-- <div class="btns-look" v-if="currentFile && currentFile.filePath">
            <el-button
              icon="el-icon-bottom"
              circle
              @click="dowloadHandle"
              v-permissions="'database#download'"
            ></el-button>
          </div> -->
        </div>
      </div>

      <!-- 去备课 -->
      <div
        class="content-lesson"
        :class="{ 'content-lesson-click': isContentLesson }"
      >
        <div class="body_content">
          <p class="lesson-my">我的备课任务</p>

          <div class="lesson-info">
            <p v-if="[1, 2, 3, 4, 5].includes(prepareLesson.checkStatus)">
              提交时间：{{ prepareLesson.createTime }}
            </p>
            <p v-if="[1, 3].includes(prepareLesson.checkStatus)">
              审核状态：
              <span class="lesson-result" style="color: rgba(250, 173, 20, 1)">
                <i class="lesson-radius">·</i>审核中</span
              >
            </p>

            <p v-if="[2, 4, 5].includes(prepareLesson.checkStatus)">
              审核结果：
              <span
                class="lesson-result"
                v-show="prepareLesson.checkStatus === 5"
                style="color: rgba(252, 81, 79, 1)"
              >
                <i class="lesson-radius">·</i>不通过</span
              >

              <span
                class="lesson-result"
                v-show="prepareLesson.checkStatus !== 5"
                style="color: rgba(26, 175, 167, 1)"
              >
                <i class="lesson-radius">·</i>已通过</span
              >
            </p>
            <p v-if="[2, 4, 5].includes(prepareLesson.checkStatus)">
              审核时间：{{ prepareLesson.checkTime }}
            </p>
            <div v-if="[2, 4].includes(prepareLesson.checkStatus)">
              备课评分：
                <span class="lesson-span lesson-right-span">{{
                  prepareLesson.score
                }}</span>
              <p v-if="prepareLesson.score < 60 ? false : true">
                <!-- 年级评分 -->
                <!-- <span class="lesson-span lesson-right-span">{{
                  prepareLesson.score
                }}</span> -->
                <!-- 校区评分 <span class="lesson-span ">{{prepareLesson.score}}</span> -->
              </p>
              <span v-else>暂无评分</span>
            </div>
            <p v-if="[2, 4, 5].includes(prepareLesson.checkStatus)">
              审核人: {{ prepareLesson.reviewerName }}
            </p>

            <p v-if="[5].includes(prepareLesson.checkStatus)">
              备课点评：
              <span
                v-show="[5].includes(prepareLesson.checkStatus) && !textListL"
                >暂无点评</span
              >
            </p>
            <div
              v-show="[5].includes(prepareLesson.checkStatus) && textListL"
              class="pIndent"
              v-html="textListL"
            ></div>
            <div
              class="img_dv_auto"
              v-show="
                [5].includes(prepareLesson.checkStatus) &&
                noResonListImgs &&
                noResonListImgs.length !== 0
              "
            >
              <div
                v-for="(item, i) in noResonListImgs"
                :key="i"
                v-html="item"
                class="img_dv"
                @click="enlarge(item)"
              ></div>
            </div>
          </div>
        </div>
        <div class="upload_teach">
          <img
            v-show="[2, 4].includes(prepareLesson.checkStatus)"
            src="/src/assets/prepare-teach/passImg.png"
            alt=""
          />

          <img
            v-show="
              [5].includes(prepareLesson.checkStatus) &&
              prepareLesson.refuseType.indexOf('1') !== -1
            "
            src="/src/assets/prepare-teach/faildImg.png"
            alt=""
          />

          <p class="bottomColor">
            <span class="spanColor" v-if="userPrepareConfig.teachPlan">*</span>
            <span class="spanColor" v-else style="visibility: hidden">*</span>
            教案
            <el-button
              v-if="
                [3, 5, 0].includes(prepareLesson.checkStatus) ||
                !prepareLesson.checkStatus
              "
              type="primary"
              size="mini"
              class="upload_btns"
              @click="uploadMyPlan('ja')"
            >
              <img src="/src/assets/prepare-teach/add.png" alt="" />
              上传
            </el-button>
          </p>
          <div
            class="upload_imgs"
            v-for="(item, index) in righFileListJa"
            :key="index"
          >
            <img :src="domain + item.imgPath" alt="" />
            <p class="upload-font">{{ item.fileName }}</p>
            <div class="btn-preview">
              <div>
                <i
                  v-if="[0, 1, 2, 3, 4, 5].includes(prepareLesson.checkStatus)"
                  class="el-icon-search-de"
                  @click="preview(item)"
                  ><span>预览</span></i
                >
                <i
                  v-if="[0, 5].includes(prepareLesson.checkStatus)"
                  class="el-icon-delete-de"
                  @click="deleted(item)"
                  ><span>删除</span></i
                >
              </div>
            </div>
          </div>
        </div>
        <!-- *************未通过***************** -->
        <div class="upload_teach">
          <img
            v-show="[2, 4].includes(prepareLesson.checkStatus)"
            src="/src/assets/prepare-teach/passImg.png"
            alt=""
          />
          <img
            v-show="
              [5].includes(prepareLesson.checkStatus) &&
              prepareLesson.refuseType.indexOf('2') !== -1
            "
            src="/src/assets/prepare-teach/faildImg.png"
            alt=""
          />

          <p class="bottomColorSk">
            <span class="spanColor" v-if="userPrepareConfig.reviewVideo"
              >*</span
            >
            <span class="spanColor" v-else style="visibility: hidden">*</span>
            说课视频
            <el-button
              v-if="
                [0, 3, 5].includes(prepareLesson.checkStatus) ||
                !prepareLesson.checkStatus
              "
              type="primary"
              size="mini"
              class="upload_btns_speak"
              @click="uploadMyPlan('sksp')"
            >
              <img src="/src/assets/prepare-teach/add.png" alt="" />
              上传
            </el-button>
          </p>
          <div
            class="upload_imgs"
            v-for="(item, index) in righFileListSp"
            :key="index"
          >
            <img :src="domain + item.imgPath" alt="" />
            <p class="upload-font">{{ item.fileName }}</p>
            <div class="btn-preview">
              <div>
                <i
                  v-if="[0, 1, 2, 3, 4, 5].includes(prepareLesson.checkStatus)"
                  class="el-icon-search-de"
                  @click="preview(item)"
                  ><span>预览</span></i
                >
                <i
                  v-if="[0, 5].includes(prepareLesson.checkStatus)"
                  class="el-icon-delete-de"
                  @click="deleted(item)"
                  ><span>删除</span></i
                >
              </div>
            </div>
          </div>
        </div>
        <p style="font-size: 12px; margin-left: 15px">
          提示：标<i style="color: red">*</i>任务为必须完成任务，请完成后再提交
        </p>
        <!-- <div class="menu-btns" @click="menuBtns">{{isContentLesson ? '我的' : '收起'}}</div> -->
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { ref, inject, reactive, toRefs, nextTick } from "vue";
import MyPlanUpload from "./my-plan-upload.vue";
import { ElMessage, ElLoading, ElMessageBox } from "element-plus";
import $, { emitter } from "$";
import PageView from "./pageView.vue";
import Moment from "moment";
import AEditContent from "@/views/handout/index.vue";
import ChooseClass from "./choose-class.vue";
import ViewCourse from "@/views/prepare-teach/components/view-course.vue";

export default {
  components: { PageView, AEditContent },
  props: {
    id: String,
    title: String,
  },
  setup(props) {
    emitter.on("handout-init", () => {
      request("");
      lookHandle();
      queryPrepareLessonByCourseIndexId();
    });
    let close: any = inject("close");
    let domain = import.meta.env.VITE_APP_BASE_URL;
    let tabType = ref(null);
    let isKeep = ref(false);

    let isContentLesson = ref(false);
    const menuBtns = () => {
      isContentLesson.value = !isContentLesson.value;
    };

    /*---------获取上部展示数据------------*/
    let courseDto: any = ref({});
    let prepareLesson: any = ref({});
    let userPrepareConfig: any = ref({});
    let noResonListImgs: any = ref([]);
    let textListL: any = ref("");
    let iframePath = ref("");
    let paperDom = ref();
    let queryPrepareLessonByCourseIndexId = () => {
      $.http
        .post("/admin/prepareLesson/queryPrepareLessonByCourseIndexId", {
          courseIndexId: props.id,
        })
        .then((res) => {
          if (res.result) {
            courseDto.value = res.json.courseDto || {};
            res.json.prepareLesson
              ? (prepareLesson.value = res.json.prepareLesson)
              : {};
            prepareLesson.value.checkTime = Moment(
              prepareLesson.value.checkTime
            ).format("YYYY-MM-DD HH:mm:ss");

            let reg = /(<.*?>)/;
            let regList =
              prepareLesson.value.refuseReason &&
              prepareLesson.value.refuseReason.split(reg);
            regList &&
              regList.forEach((item: any) => {
                if (item.indexOf("<img") !== -1) {
                  noResonListImgs.value.push(item);
                } else {
                  textListL.value += item;
                }
              });
            userPrepareConfig.value = res.json.userPrepareConfig || {};
          }
        });
    };
    queryPrepareLessonByCourseIndexId();
    /**--------------onload---------- */
    let loading = ref();
    let onload = () => {
      loading.value.close();
    };
    /*---------获取tab标签数据------------*/
    let tabCountList = ref([
      // { name: '全部', nameKey: 'totalCount', num: 0, type: null },
      { name: "全部资料", nameKey: "totalCount", num: 0, type: 0 },
      { name: "课件", nameKey: "courseWareCount", num: 0, type: 1 },
      { name: "讲义", nameKey: "handoutCount", num: 0, type: 2 },
      { name: "教案", nameKey: "teachplanCount", num: 0, type: 5 },
      { name: "说课视频", nameKey: "mediaCount", num: 0, type: 3 },
      { name: "试卷", nameKey: "paperCount", num: 0, type: 7 },
      { name: "多媒体", nameKey: "multimediaCount", num: 0, type: 6 },
      { name: "其他", nameKey: "otherCount", num: 0, type: 4 },
    ]);
    /*--------- 重新备课---------------*/
    const resentPrepareHandler = () => {
      ElMessageBox.confirm(
        "重新备课后，原来的审核结果将无效是否确定重新备课？",
        "确认信息",
        {
          distinguishCancelAndClose: true,
          confirmButtonText: "确定",
          cancelButtonText: "暂不",
        }
      )
        .then(() => {
          let __params = {
            checkStatus: 0,
            prepareLessonId: prepareLesson.value.id,
          };
          $.http
            .post("/admin/prepareLesson/changePrepareLessonStatus", __params)
            .then((res) => {
              if (res.result) {
                ElMessage.success("重新备课成功");
                lookHandle();
                request("");
                queryPrepareLessonByCourseIndexId();
                tabCountRequest();
              } else {
                ElMessage.error(res.json);
              }
            });
        })
        .catch(() => {
          ElMessage({ type: "info", message: "放弃重新备课" });
        });
    };
    /*---------提交备课------------*/
    const savePrepareClass = () => {
      if (
        userPrepareConfig.value.teachPlan &&
        righFileListJa.value.length === 0
      )
        return ElMessage.error("教案不能为空");
      if (
        userPrepareConfig.value.reviewVideo &&
        righFileListSp.value.length === 0
      )
        return ElMessage.error("说课视频不能为空");
      let __params = {
        courseId: courseDto.value.id,
        courseIndexId: courseDto.value.courseIndexId,
        prepareLessonId: prepareLesson.value.id,
      };
      $.http
        .post("/admin/prepareLesson/submitPrepareLessonById", __params)
        .then((res) => {
          if (res.result) {
            //tip 重新备课刷新当前页面 不回到列表页面
            ElMessage.success("提交成功");
            emitter.emit("curriculum-papers-submit");
            close(res.result);
          } else {
            ElMessage.error(res.json);
          }
        });
    };
    /*----------获取右侧数据-------------------*/
    let righFileListJa: any = ref([]);
    let righFileListSp: any = ref([]);
    const lookHandle = async () => {
      righFileListSp.value = [];
      righFileListJa.value = [];
      let res = await $.http.post(
        "/admin/prepareLesson/queryPrepareMaterials",
        { courseIndexId: props.id }
      );
      if (res.result) {
        res.json &&
          res.json.forEach((item) => {
            if (item.type === 3) righFileListSp.value.push(item);
            if (item.type === 5) righFileListJa.value.push(item);
          });
      }
    };
    lookHandle();
    const toteach = () => {
      $.screen.create(ViewCourse, { id: props.id  }, { zIndex: "2010", hiddenBack: true });
      // $.screen
      //   .create(ChooseClass, { title: "选择班级", id: props.id })
      //   .then((data: any) => {
      //     if (data) {
      //       close(data);
      //     }
      //   })
      //   .catch((data: any) => {});
    };
    /*---------获取内容图片数据------------*/
    let allFileList = ref([]);
    const request = async (type, isnot?: any) => {
      let res = await $.http.post("/admin/prepareLesson/queryMaterialByCourseIndexId", { courseIndexId: props.id, type: type ? type : 0 });
      if (res.result) {
        allFileList.value = res.json.sort((a, b) => a.resCreateTime - b.resCreateTime);
        //如果存在 直接默认选中当前项
        if (isnot) data.isbg = 0;
        onCardHandle(data.allFileList[0], 0);
      }
    };
    request("");
    /*----------数量----------------------*/
    const tabCountRequest = async () => {
      let res = await $.http.post(
        "/admin/prepareLesson/queryMaterialCountByCourseIndexId",
        { courseIndexId: props.id }
      );
      if (res.result) {
        let arr = Object.entries(res.json);
        arr.map(([key, value]) => {
          tabCountList.value.map((item: any) => {
            if (item.nameKey == key) {
              return (item.num = value);
            }
          });
        });
      }
    };
    tabCountRequest();
    /*-----删除-----*/
    const deleted = async (item: any) => {
      await $.http.post("/admin/prepareLesson/deletePrepareMaterial", {
        courseIndexId: props.id,
        materialId: item.id,
      });
      request("");
      lookHandle();
    };
    /*-----预览-----*/
    const preview = (item) => {
      if (item.mediaType === "url") {
        window.open(item.filePath);
      } else {
        const loading = ElLoading.service({
          lock: true,
          background: "rgba(255, 255, 255, .7)",
          text: "加载中...",
        });
        let src = `${$.utils.generatBasePath()}furl=${import.meta.env.VITE_APP_BASE_URL}${item.filePath}`;
        let closeBtn = $.element("div", {
          className: "el-icon-close",
          style: {
            width: "36px",
            height: "36px",
            lineHeight: "36px",
            textAlign: "center",
            background: "#fff",
            borderRadius: "50%",
            fontSize: "24px",
            position: "fixed",
            top: "40px",
            right: "40px",
            zIndex: "10",
            cursor: "pointer",
          },
          on: {
            click: () => {
              container.remove();
            },
          },
        });
        let container;
        if (item.ext === "mp4") {
          let video = $.element("video", {
            attrs: {
              src: `${import.meta.env.VITE_APP_BASE_URL}${item.filePath}`,
              width: "100%",
              height: "100%",
              controls: "true",
              controlsList: "nodownload",
            },
            style: { background: "#f9f9f9" },
          });
          video.oncanplay = loading.close;
          container = $.element(
            "div",
            {
              style: {
                width: "100%",
                height: "100%",
                position: "absolute",
                top: "0",
                left: "0",
                zIndex: "2012",
                background: "rgba(0,0,0,.8)",
              },
            },
            [closeBtn, video]
          );
        } else if (item.ext === null && item.mediaType === "url") {
          loading.close();
          let url = $.element(
            "p",
            {
              style: {
                background: "#f9f9f9",
                width: "100%",
                height: "100%",
                padding: "36px",
                fontSize: "20px",
              },
            },
            "链接地址：" + item.filePath
          );
          container = $.element(
            "div",
            {
              style: {
                width: "100%",
                height: "100%",
                position: "absolute",
                top: "0",
                left: "0",
                zIndex: "2012",
                background: "rgba(0,0,0,.8)",
              },
            },
            [closeBtn, url]
          );
        } else {
          let iframe = $.element("iframe", {
            attrs: { src, width: "100%", height: "100%" },
            style: { background: "#f9f9f9" },
          });
          iframe.onload = loading.close;
          container = $.element(
            "div",
            {
              style: {
                width: "100%",
                height: "100%",
                position: "absolute",
                top: "0",
                left: "0",
                zIndex: "2012",
                background: "rgba(0,0,0,.8)",
              },
            },
            [closeBtn, iframe]
          );
        }
        document.body.appendChild(container);
      }
    };
    /*---------上传我的教案------------*/
    const uploadMyPlan = (type: string) => {
      let accept: any = null;
      if (type === "sksp") accept = ".mp4,.jpg,.jpeg,.png";
      if (type === "ja") accept = ".doc,.docx,.pdf";
      $.modal
        .create({
          title: "上传我的说课",
          width: 640,
          component: MyPlanUpload,
          props: { id: props.id, accept: accept, type },
          zIndex: 2011,
        })
        .finally(() => {
          request("");
          lookHandle();
          queryPrepareLessonByCourseIndexId();
        });
    };
    let currentFile: any = reactive({});
    let isCardbg: any = ref();
    let onCardHandle = (item, index) => {
      data.isCardbg = index;
      data.currentFile = {};
      let timer = setTimeout(() => {
        clearTimeout(timer);
        data.currentFile = item;
        if (item.sourceFrom === 3) {
          iframePath.value = `${$.utils.generatBasePath()}furl=${
            import.meta.env.VITE_APP_BASE_URL
          }${item.filePath}`;
        } else {
          iframePath.value = `./#/test-paper-edit/true/${item.id}?showDownload=false&whiteStyle=white-style`;
          nextTick(() => {
            paperDom.value?.contentDocument.location.reload(true);
          });
        }
      });

      // loading.value = ElLoading.service({ lock: true, background: 'rgba(255, 255, 255, .7)', text: '加载中...' })
    };
    let dowloadHandle = () => $.element("a", {attrs: {href: domain + data.currentFile.filePath, download: `${data.currentFile.fileName}.${data.currentFile.ext}`, target: "_blank",}}).click();
    // let printpage = () => {
    //   window.open(
    //     `${import.meta.env.VITE_APP_OFFICE_WEB365}info=2&furl=${domain}${
    //       data.currentFile.filePath
    //     }`
    //   );
    // };
    let onMenuHandle = (item: any, index: any) => {
      data.isbg = item.type;
      request(item.type);
    };

    let isbg = ref(0);
    const data = reactive({
      isbg,
      isCardbg,
      allFileList,
      domain,
      currentFile,
      isKeep,
    });
    const enlarge = (item: any) => {
      let reg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
      let src = item.match(reg);
      const img = new Image();
      img.src = src[1];
      const newWin: any = window.open("", "_blank");
      newWin.document.write(img.outerHTML);
      newWin.document.title = "流程图";
      newWin.document.close();
    };

    return {
      ...toRefs(data),
      enlarge,
      tabCountList,
      onMenuHandle,
      uploadMyPlan,
      onCardHandle,
      righFileListJa,
      righFileListSp,
      preview,
      deleted,
      resentPrepareHandler,
      // printpage,
      dowloadHandle,
      isContentLesson,
      menuBtns,
      close,
      courseDto,
      prepareLesson,
      noResonListImgs,
      userPrepareConfig,
      savePrepareClass,
      tabType,
      textListL,
      loading,
      onload,
      toteach,
      iframePath,
      paperDom,
    };
  },
};
</script>
<style lang="scss" scoped>
@import "./../index.scss";
</style>
